package com.ruoyi.statisticalCenter.service.impl;

import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.util.BeanUtil;
import com.github.pagehelper.PageHelper;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.domain.vo.InitTableVo;
import com.ruoyi.common.domain.vo.TableVo;
import com.ruoyi.common.service.TableService;
import com.ruoyi.common.utils.GetDateStringUtils;
import com.ruoyi.hqfinance.domain.HqNetworkBillDetail;
import com.ruoyi.hqfinance.mapper.HqNetworkBillDetailMapper;
import com.ruoyi.logistic.domain.PageDate;
import com.ruoyi.logistic.domain.PageInfo;
import com.ruoyi.logistic.domain.ScWeightFlowDirectionMonitoringDetail;
import com.ruoyi.logistic.mapper.ScWeightFlowDirectionMonitoringDetailMapper;
import com.ruoyi.statisticalCenter.domain.ScWeightFlowDirectionMonitoringClient;
import com.ruoyi.statisticalCenter.domain.vo.DateStrVo;
import com.ruoyi.statisticalCenter.domain.vo.ScWeightFlowDirectionDispositionPointVo;
import com.ruoyi.statisticalCenter.domain.vo.ScWeightFlowDirectionDispositionVo;
import com.ruoyi.statisticalCenter.domain.vo.ScWeightFlowDirectionMonitoringVo;
import com.ruoyi.statisticalCenter.mapper.ScWeightFlowDirectionMonitoringClientMapper;
import com.ruoyi.statisticalCenter.mapper.ScWeightFlowDirectionMonitoringNewMapper;
import com.ruoyi.statisticalCenter.utils.BigDecimalUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.statisticalCenter.mapper.ScWeightFlowDirectionMonitoringMapper;
import com.ruoyi.statisticalCenter.domain.ScWeightFlowDirectionMonitoring;
import com.ruoyi.statisticalCenter.service.IScWeightFlowDirectionMonitoringService;
import com.ruoyi.common.core.text.Convert;

/**
 * 均重流向监控Service业务层处理
 *
 * @author pyx
 * @date 2024-03-01
 */
@Service
public class ScWeightFlowDirectionMonitoringServiceImpl implements IScWeightFlowDirectionMonitoringService {
    @Autowired
    private ScWeightFlowDirectionMonitoringMapper scWeightFlowDirectionMonitoringMapper;
    @Autowired
    private TableService tableService;
    @Autowired
    private HqNetworkBillDetailMapper hqNetworkBillDetailMapper;
    @Autowired
    private ScWeightFlowDirectionMonitoringNewMapper scWeightFlowDirectionMonitoringNewMapper;
    @Autowired
    private ScWeightFlowDirectionMonitoringClientMapper clientMapper;

    @Autowired
    private ScWeightFlowDirectionMonitoringDetailMapper detailMapper;

    MathContext mc = new MathContext(3, RoundingMode.HALF_UP); // 设置精度为3位，采用四舍五入模式


    @Override
    public R collectList(ScWeightFlowDirectionMonitoringVo vo, OutputStream outputStream) {

        PageHelper.startPage(vo.getPageDate());
        if (vo.getNetworkLevel() == 0) {
            List<ScWeightFlowDirectionMonitoring> list = collectNet(vo);
            Workbook workbook = new XSSFWorkbook(); // 创建一个新的Excel工作簿
            Sheet sheet = workbook.createSheet("Amount Data"); // 创建一个新的工作表
            // 创建边框样式
            CellStyle borderStyle = workbook.createCellStyle();
            BorderStyle thin = BorderStyle.THIN;
            short blackColorIndex = IndexedColors.BLACK.getIndex();
            borderStyle.setBorderTop(thin);
            borderStyle.setBorderBottom(thin);
            borderStyle.setBorderLeft(thin);
            borderStyle.setBorderRight(thin);
            borderStyle.setTopBorderColor(blackColorIndex);
            borderStyle.setBottomBorderColor(blackColorIndex);
            borderStyle.setLeftBorderColor(blackColorIndex);
            borderStyle.setRightBorderColor(blackColorIndex);

            // 创建表头样式
            CellStyle headerStyle = workbook.createCellStyle();
            Font headerFont = workbook.createFont();
            headerFont.setBold(true);
            headerFont.setFontHeightInPoints((short) 14); // 设置字体大小
            headerStyle.setFont(headerFont);
            headerStyle.setAlignment(HorizontalAlignment.CENTER); // 设置水平居中
            headerStyle.setVerticalAlignment(VerticalAlignment.CENTER); // 设置垂直居中
            headerStyle.setBorderTop(thin);
            headerStyle.setBorderBottom(thin);
            headerStyle.setBorderLeft(thin);
            headerStyle.setBorderRight(thin);
            headerStyle.setTopBorderColor(blackColorIndex);
            headerStyle.setBottomBorderColor(blackColorIndex);
            headerStyle.setLeftBorderColor(blackColorIndex);
            headerStyle.setRightBorderColor(blackColorIndex);
            String[] cellName = {
                    "统计日期", "承包区名称", "发件票数", "包仓票数", "包仓重量", "日考核重量", "考核标准", "止损考核", "包仓均重", "均重指标", "均重考核标准", "均重考核", "宁夏票数", "甘肃票数", "青海票数", "海南票数", "流向票数合计", "流向占比", "流向指标", "流向考核"
            };
            Row headerRow = sheet.createRow(0);
            for (int i = 0; i < cellName.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(cellName[i]);
                cell.setCellStyle(headerStyle);
            }
            int rowNum = 1; // 行索引从1开始（因为已经有表头行）
            for (ScWeightFlowDirectionMonitoring monitoring : list) {
                Row dataRow = sheet.createRow(rowNum++);
                Cell cell0 = dataRow.createCell(0);
                cell0.setCellValue(monitoring.getSettleDate());
                cell0.setCellStyle(borderStyle);
                Cell cell1 = dataRow.createCell(1);
                cell1.setCellValue(monitoring.getContractArea());
                cell1.setCellStyle(borderStyle);
                Cell cell2 = dataRow.createCell(2);
                cell2.setCellValue(monitoring.getSendTicket());
                cell2.setCellStyle(borderStyle);
                Cell cell3 = dataRow.createCell(3);
                cell3.setCellValue(monitoring.getStockCount());
                cell3.setCellStyle(borderStyle);
                Cell cell4 = dataRow.createCell(4);
                cell4.setCellValue(monitoring.getBaleWeight().doubleValue());
                cell4.setCellStyle(borderStyle);

                // 止损考核
                Cell cell5 = dataRow.createCell(5);
                cell5.setCellValue(monitoring.getDailyAssessWeight().doubleValue());
                cell5.setCellStyle(borderStyle);
                Cell cell6 = dataRow.createCell(6);
                cell6.setCellValue(monitoring.getAssessmentStandard().doubleValue());
                cell6.setCellStyle(borderStyle);
                Cell cell7 = dataRow.createCell(7);
                cell7.setCellValue(monitoring.getStopLossAssessment().doubleValue());
                cell7.setCellStyle(borderStyle);

                // 均重考核

                Cell cell8 = dataRow.createCell(8);
                cell8.setCellValue(monitoring.getPackingWarehouseWeight().doubleValue());
                cell8.setCellStyle(borderStyle);
                Cell cell9 = dataRow.createCell(9);
                cell9.setCellValue(monitoring.getAverageWeightIndex().doubleValue());
                cell9.setCellStyle(borderStyle);
                Cell cell10 = dataRow.createCell(10);
                cell10.setCellValue(monitoring.getWeightAssessmentStandard().doubleValue());
                cell10.setCellStyle(borderStyle);
                Cell cell11 = dataRow.createCell(11);
                cell11.setCellValue(monitoring.getWeightAssessment().doubleValue());
                cell11.setCellStyle(borderStyle);

                // 流向考核
                Cell cell12 = dataRow.createCell(12);
                cell12.setCellValue(monitoring.getNingxiaVotes());
                cell12.setCellStyle(borderStyle);
                Cell cell13 = dataRow.createCell(13);
                cell13.setCellValue(monitoring.getGansuVotes());
                cell13.setCellStyle(borderStyle);
                Cell cell14 = dataRow.createCell(14);
                cell14.setCellValue(monitoring.getQinghaiVotes());
                cell14.setCellStyle(borderStyle);
                Cell cell15 = dataRow.createCell(15);
                cell15.setCellValue(monitoring.getHainanVotes());
                cell15.setCellStyle(borderStyle);
                Cell cell16 = dataRow.createCell(16);
                cell16.setCellValue(monitoring.getFlowTally());
                cell16.setCellStyle(borderStyle);
                Cell cell17 = dataRow.createCell(17);
                cell17.setCellValue(monitoring.getFlowRatio().doubleValue());
                cell17.setCellStyle(borderStyle);
                Cell cell18 = dataRow.createCell(18);
                cell18.setCellValue(monitoring.getDirectionIndicator().doubleValue());
                cell18.setCellStyle(borderStyle);
                Cell cell19 = dataRow.createCell(19);
                cell19.setCellValue(monitoring.getFlowDirectionTest().doubleValue());
                cell19.setCellStyle(borderStyle);
            }
            try {
                workbook.write(outputStream); // 将工作簿写入输出流
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                workbook.close(); // 关闭工作簿
            } catch (IOException e) {
                e.printStackTrace();
            }
            return R.ok(list);
        }
        if (vo.getNetworkLevel() == 1) {
            List<ScWeightFlowDirectionMonitoringClient> list = collectClient(vo);
            Workbook workbook = new XSSFWorkbook(); // 创建一个新的Excel工作簿
            Sheet sheet = workbook.createSheet("Amount Data"); // 创建一个新的工作表
            // 创建边框样式
            CellStyle borderStyle = workbook.createCellStyle();
            BorderStyle thin = BorderStyle.THIN;
            short blackColorIndex = IndexedColors.BLACK.getIndex();
            borderStyle.setBorderTop(thin);
            borderStyle.setBorderBottom(thin);
            borderStyle.setBorderLeft(thin);
            borderStyle.setBorderRight(thin);
            borderStyle.setTopBorderColor(blackColorIndex);
            borderStyle.setBottomBorderColor(blackColorIndex);
            borderStyle.setLeftBorderColor(blackColorIndex);
            borderStyle.setRightBorderColor(blackColorIndex);

            // 创建表头样式
            CellStyle headerStyle = workbook.createCellStyle();
            Font headerFont = workbook.createFont();
            headerFont.setBold(true);
            headerFont.setFontHeightInPoints((short) 14); // 设置字体大小
            headerStyle.setFont(headerFont);
            headerStyle.setAlignment(HorizontalAlignment.CENTER); // 设置水平居中
            headerStyle.setVerticalAlignment(VerticalAlignment.CENTER); // 设置垂直居中
            headerStyle.setBorderTop(thin);
            headerStyle.setBorderBottom(thin);
            headerStyle.setBorderLeft(thin);
            headerStyle.setBorderRight(thin);
            headerStyle.setTopBorderColor(blackColorIndex);
            headerStyle.setBottomBorderColor(blackColorIndex);
            headerStyle.setLeftBorderColor(blackColorIndex);
            headerStyle.setRightBorderColor(blackColorIndex);
            String[] cellName = {
                    "统计日期", "承包区名称", "发件票数", "包仓票数", "包仓重量", "包仓均重", "宁夏票数", "甘肃票数", "青海票数", "海南票数", "流向票数合计", "流向占比"
            };
            Row headerRow = sheet.createRow(0);
            for (int i = 0; i < cellName.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(cellName[i]);
                cell.setCellStyle(headerStyle);
            }
            int rowNum = 1; // 行索引从1开始（因为已经有表头行）
            for (ScWeightFlowDirectionMonitoringClient monitoring : list) {
                Row dataRow = sheet.createRow(rowNum++);
                Cell cell0 = dataRow.createCell(0);
                cell0.setCellValue(monitoring.getSettleDate());
                cell0.setCellStyle(borderStyle);

                Cell cell1 = dataRow.createCell(1);
                cell1.setCellValue(monitoring.getContractArea());
                cell1.setCellStyle(borderStyle);
                Cell cell2 = dataRow.createCell(2);
                cell2.setCellStyle(borderStyle);

                if (monitoring.getSendTicket() != null) {
                    cell2.setCellValue(monitoring.getSendTicket());
                } else {
                    cell2.setCellValue(0.0);

                }

                Cell cell3 = dataRow.createCell(3);
                cell3.setCellStyle(borderStyle);
                if (monitoring.getStockCount() != null) {
                    cell3.setCellValue(monitoring.getStockCount());
                } else {
                    cell3.setCellValue(0);
                }

                Cell cell4 = dataRow.createCell(4);
                cell4.setCellStyle(borderStyle);
                if (monitoring.getBaleWeight() != null) {
                    cell4.setCellValue(monitoring.getBaleWeight().doubleValue());
                } else {
                    cell4.setCellValue(0);
                }

                Cell cell5 = dataRow.createCell(5);
                cell5.setCellStyle(borderStyle);
                if (monitoring.getPackingWarehouseWeight() != null) {
                    cell5.setCellValue(monitoring.getPackingWarehouseWeight().doubleValue());
                } else {
                    cell5.setCellValue(0);
                }

                // 流向考核
                Cell cell6 = dataRow.createCell(6);
                cell6.setCellStyle(borderStyle);
                if (monitoring.getNingxiaVotes() != null) {
                    cell6.setCellValue(monitoring.getNingxiaVotes());
                } else {
                    cell6.setCellValue(0);
                }

                Cell cell7 = dataRow.createCell(7);
                cell7.setCellStyle(borderStyle);
                if (monitoring.getGansuVotes() != null) {
                    cell7.setCellValue(monitoring.getGansuVotes());
                } else {
                    cell7.setCellValue(0);
                }

                Cell cell8 = dataRow.createCell(8);
                cell8.setCellStyle(borderStyle);
                if (monitoring.getQinghaiVotes() != null) {
                    cell8.setCellValue(monitoring.getQinghaiVotes());
                } else {
                    cell8.setCellValue(0);
                }

                Cell cell9 = dataRow.createCell(9);
                cell9.setCellStyle(borderStyle);
                if (monitoring.getHainanVotes() != null) {
                    cell9.setCellValue(monitoring.getHainanVotes());
                } else {
                    cell9.setCellValue(0);
                }

                Cell cell10 = dataRow.createCell(10);
                cell10.setCellStyle(borderStyle);
                if (monitoring.getFlowTally() != null) {
                    cell10.setCellValue(monitoring.getFlowTally());
                } else {
                    cell10.setCellValue(0);
                }

                Cell cell11 = dataRow.createCell(11);
                cell11.setCellStyle(borderStyle);
                if (monitoring.getFlowRatio() != null) {
                    double v = monitoring.getFlowRatio().doubleValue();
                    DecimalFormat format = new DecimalFormat("#.##");
                    cell11.setCellValue(format.format(v));
                } else {
                    cell11.setCellValue(0.0);
                }
            }
            try {
                workbook.write(outputStream); // 将工作簿写入输出流
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                workbook.close(); // 关闭工作簿
            } catch (IOException e) {
                e.printStackTrace();
            }
            return R.ok(list);
        }
        return R.fail();

    }

    @Override
    public List<ScWeightFlowDirectionMonitoring> collectNet(ScWeightFlowDirectionMonitoringVo vo) {
        List<ScWeightFlowDirectionMonitoring> list = detailMapper.selectScWeightFlowDirectionMonitoring0(vo);
        if (list == null || list.size() == 0) {
            list = scWeightFlowDirectionMonitoringNewMapper.collect(vo);
            for (ScWeightFlowDirectionMonitoring monitoring : list) {
                // 包仓内票数
                Integer stockCount = monitoring.getSendTicket() - scWeightFlowDirectionMonitoringNewMapper.stockCount(vo.getStartTime(), vo.getEndTime());
                monitoring.setStockCount(stockCount);
                //包仓内重量
                BigDecimal baleWeight = scWeightFlowDirectionMonitoringNewMapper.baleWeight(vo.getStartTime(), vo.getEndTime());
                monitoring.setBaleWeight(baleWeight);
                //止损考核
                if (monitoring.getBaleWeight().compareTo(monitoring.getDailyAssessWeight()) > 0) {
                    BigDecimal stopLossAssessment = monitoring.getBaleWeight().subtract(monitoring.getDailyAssessWeight());
                    monitoring.setStopLossAssessment(stopLossAssessment);
                } else {
                    monitoring.setStopLossAssessment(BigDecimal.ZERO);
                }
                // 均重考核-包仓均重
                monitoring.setPackingWarehouseWeight(baleWeight.divide(BigDecimal.valueOf(stockCount), mc));
                if (monitoring.getPackingWarehouseWeight().compareTo(monitoring.getAverageWeightIndex()) > 0) {
                    BigDecimal weightAssessment = (monitoring.getPackingWarehouseWeight().subtract(monitoring.getAverageWeightIndex()).multiply(BigDecimal.valueOf(stockCount)).multiply(monitoring.getWeightAssessmentStandard()));
                    monitoring.setWeightAssessment(weightAssessment);
                } else {
                    monitoring.setWeightAssessment(BigDecimal.ZERO);
                }
                // 流向票数合计
                Integer flowTally = monitoring.getNingxiaVotes() + monitoring.getGansuVotes() + monitoring.getQinghaiVotes() + monitoring.getHainanVotes();
                monitoring.setFlowTally(flowTally);
                monitoring.setFlowRatio(BigDecimal.valueOf(flowTally).divide(BigDecimal.valueOf(monitoring.getSendTicket()), 2, BigDecimal.ROUND_UP));
                if (monitoring.getFlowRatio().compareTo(monitoring.getDirectionIndicator()) > 0) {
                    BigDecimal flowDirectionTest = monitoring.getDirectionStandard().multiply(BigDecimal.valueOf(flowTally));
                    monitoring.setFlowDirectionTest(flowDirectionTest);
                } else {
                    monitoring.setFlowDirectionTest(BigDecimal.ZERO);
                }
            }
        }

        return list;
    }

    @Override
    public List<ScWeightFlowDirectionMonitoringClient> collectClient(ScWeightFlowDirectionMonitoringVo vo) {
        List<ScWeightFlowDirectionMonitoringClient> list = detailMapper.selectScWeightFlowDirectionMonitoring1(vo);
        if (list == null || list.size() == 0) {
            list = clientMapper.collectClient(vo);
            for (ScWeightFlowDirectionMonitoringClient client : list) {

                Integer flowTally = Optional.ofNullable(client.getNingxiaVotes())
                        .orElse(0) +
                        Optional.ofNullable(client.getGansuVotes())
                                .orElse(0) +
                        Optional.ofNullable(client.getQinghaiVotes())
                                .orElse(0) +
                        Optional.ofNullable(client.getHainanVotes())
                                .orElse(0);
                client.setFlowTally(flowTally);
                if (client != null && client.getSendTicket() != null && client.getSendTicket() != 0) {
                    client.setFlowRatio(BigDecimal.valueOf(flowTally).divide(BigDecimal.valueOf(client.getSendTicket()), mc));
                } else {
                    client.setFlowRatio(BigDecimal.ZERO);
                }
            }
        }
        return list;
    }

    @Override
    public R updateDisposition(ScWeightFlowDirectionDispositionVo scWeightFlowDirectionDispositionVo) {
        //scWeightFlowDirectionDispositionVo.setId("1");
        //return scWeightFlowDirectionMonitoringMapper.updateDisposition(scWeightFlowDirectionDispositionVo) > 0 ? R.ok("修改成功") : R.fail("修改失败");
        //首先id为1，科设置开始日期结束日期
        if (scWeightFlowDirectionDispositionVo.getStartDate() == null) {
            return R.fail("开始时间不能为空");
        }
        ScWeightFlowDirectionDispositionVo scWeightFlowDirectionDispositionVo1 = scWeightFlowDirectionMonitoringMapper.selectByStateDate(scWeightFlowDirectionDispositionVo.getStartDate());
        if (scWeightFlowDirectionDispositionVo1 != null) {
            scWeightFlowDirectionDispositionVo.setId(scWeightFlowDirectionDispositionVo1.getId());
            return scWeightFlowDirectionMonitoringMapper.updateDisposition(scWeightFlowDirectionDispositionVo) > 0 ? R.ok("修改成功") : R.fail("修改失败");
        }

        ScWeightFlowDirectionDispositionVo scWeightFlowDirectionDispositionVo2 = scWeightFlowDirectionMonitoringMapper.selectDisposition();
        Date startDate = scWeightFlowDirectionDispositionVo.getStartDate();
        // 创建一个Calendar实例并设置为当前日期
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(startDate);

        // 从当前日期减去一天
        calendar.add(Calendar.DAY_OF_MONTH, -1);
        // 获取减去一天后的日期
        Date previousDate = calendar.getTime();

        scWeightFlowDirectionDispositionVo2.setEndDate(previousDate);
        scWeightFlowDirectionMonitoringMapper.updateDisposition(scWeightFlowDirectionDispositionVo2);

        return scWeightFlowDirectionMonitoringMapper.insertScWeightFlowDirectionMonitorin(scWeightFlowDirectionDispositionVo) > 0 ? R.ok("修改成功") : R.fail("修改失败");

    }

    @Override
    public R selectDisposition() {
        return R.ok(scWeightFlowDirectionMonitoringMapper.selectDisposition());
    }

    @Override
    public List<HqNetworkBillDetail> point(ScWeightFlowDirectionDispositionPointVo vo) {
        PageHelper.startPage(vo.getPageDate());
        if (vo.getNetworkLevel() == 0) {
            return hqNetworkBillDetailMapper.scWeightFlowPoint(vo);
        }
        if (vo.getNetworkLevel() == 1) {
            return hqNetworkBillDetailMapper.scWeightFlowClientPoint(vo);
        }
        return null;
    }

    @Override
    public R cache(DateStrVo dateStrVo) {
//        List<String> times = GetDateStringUtils.generateDatesForMonth(2024, 5);
        List<String> days = GetDateStringUtils.getDateStr(dateStrVo.getStartDateStr(), dateStrVo.getEndDateStr());
        List<String> dateStrList = detailMapper.selectllDateStr();
        days.removeAll(dateStrList);
        for (String day : days) {
            String time = day;
            Integer[] networkLevels = {0, 1};
            for (Integer networkLevel : networkLevels) {
                ScWeightFlowDirectionMonitoringVo scWeightFlowDirectionMonitoringVo = new ScWeightFlowDirectionMonitoringVo();
                scWeightFlowDirectionMonitoringVo.setNetworkLevel(networkLevel);
                PageDate pageDate = new PageDate();
                pageDate.setPageNum(1);
                pageDate.setPageSize(100000);
                scWeightFlowDirectionMonitoringVo.setPageDate(pageDate);
                scWeightFlowDirectionMonitoringVo.setStartTime(time);
                scWeightFlowDirectionMonitoringVo.setEndTime(time);
                if (networkLevel == 0) {
                    List<ScWeightFlowDirectionMonitoringDetail> scWeightFlowDirectionMonitoringDetails = new ArrayList<>();
                    List<ScWeightFlowDirectionMonitoring> scWeightFlowDirectionMonitorings = collectCache(scWeightFlowDirectionMonitoringVo);
                    for (ScWeightFlowDirectionMonitoring scWeightFlowDirectionMonitoring : scWeightFlowDirectionMonitorings) {
                        ScWeightFlowDirectionMonitoringDetail scWeightFlowDirectionMonitoringDetail = new ScWeightFlowDirectionMonitoringDetail();
                        BeanUtils.copyProperties(scWeightFlowDirectionMonitoring, scWeightFlowDirectionMonitoringDetail);
                        scWeightFlowDirectionMonitoringDetail.setNetworkLevel(String.valueOf(networkLevel));
                        scWeightFlowDirectionMonitoringDetail.setSettleDate(time);
                        scWeightFlowDirectionMonitoringDetails.add(scWeightFlowDirectionMonitoringDetail);
                    }
                    detailMapper.insertList(scWeightFlowDirectionMonitoringDetails);
                } else {
                    List<ScWeightFlowDirectionMonitoringDetail> scWeightFlowDirectionMonitoringDetails = new ArrayList<>();
                    List<ScWeightFlowDirectionMonitoringClient> scWeightFlowDirectionMonitoringClients = collectCache1(scWeightFlowDirectionMonitoringVo);
                    for (ScWeightFlowDirectionMonitoringClient scWeightFlowDirectionMonitoringClient : scWeightFlowDirectionMonitoringClients) {
                        ScWeightFlowDirectionMonitoringDetail scWeightFlowDirectionMonitoringDetail = new ScWeightFlowDirectionMonitoringDetail();
                        BeanUtils.copyProperties(scWeightFlowDirectionMonitoringClient, scWeightFlowDirectionMonitoringDetail);
                        scWeightFlowDirectionMonitoringDetail.setNetworkLevel(String.valueOf(networkLevel));
                        scWeightFlowDirectionMonitoringDetail.setSettleDate(time);
                        detailMapper.insert(scWeightFlowDirectionMonitoringDetail);
                        scWeightFlowDirectionMonitoringDetails.add(scWeightFlowDirectionMonitoringDetail);
                    }
                    //detailMapper.insertList(scWeightFlowDirectionMonitoringDetails);
                }
            }
            System.out.println(time + " 的数据缓存完成");
        }

        return R.ok();
    }

    @Override
    public R collectNew(ScWeightFlowDirectionMonitoringVo vo) {
        PageHelper.startPage(vo.getPageDate());
        if (vo.getNetworkLevel() == 0) {
            List<ScWeightFlowDirectionMonitoring> list = detailMapper.selectScWeightFlowDirectionMonitoring0(vo);
            if (list == null || list.size() == 0) {
                PageHelper.startPage(vo.getPageDate());
                list = scWeightFlowDirectionMonitoringNewMapper.collect(vo);

                //List<ScWeightFlowDirectionMonitoring> list = scWeightFlowDirectionMonitoringNewMapper.collect(vo);
                for (ScWeightFlowDirectionMonitoring monitoring : list) {
                    // 包仓内票数
                    Integer stockCount = monitoring.getSendTicket() - scWeightFlowDirectionMonitoringNewMapper.stockCount(vo.getStartTime(), vo.getEndTime());
                    monitoring.setStockCount(stockCount);
                    //包仓内重量
                    BigDecimal baleWeight = scWeightFlowDirectionMonitoringNewMapper.baleWeight(vo.getStartTime(), vo.getEndTime());
                    baleWeight = baleWeight.setScale(2, RoundingMode.HALF_UP);
                    monitoring.setBaleWeight(baleWeight);
                    //止损考核
                    if (monitoring.getBaleWeight().compareTo(monitoring.getDailyAssessWeight()) > 0) {
                        BigDecimal stopLossAssessment = monitoring.getBaleWeight().subtract(monitoring.getDailyAssessWeight());
                        monitoring.setStopLossAssessment(stopLossAssessment.multiply(monitoring.getAssessmentStandard()));
                    } else {
                        monitoring.setStopLossAssessment(BigDecimal.ZERO);
                    }
                    // 均重考核-包仓均重
                    monitoring.setPackingWarehouseWeight(baleWeight.divide(BigDecimal.valueOf(stockCount), mc));
                    if (monitoring.getPackingWarehouseWeight().compareTo(monitoring.getAverageWeightIndex()) > 0) {
                        BigDecimal weightAssessment = (monitoring.getPackingWarehouseWeight().subtract(monitoring.getAverageWeightIndex()).multiply(BigDecimal.valueOf(stockCount)).multiply(monitoring.getWeightAssessmentStandard()));
                        monitoring.setWeightAssessment(weightAssessment);
                    } else {
                        monitoring.setWeightAssessment(BigDecimal.ZERO);
                    }
                    // 流向票数合计
                    Integer flowTally = Optional.ofNullable(monitoring.getNingxiaVotes())
                            .orElse(0) +
                            Optional.ofNullable(monitoring.getGansuVotes())
                                    .orElse(0) +
                            Optional.ofNullable(monitoring.getQinghaiVotes())
                                    .orElse(0) +
                            Optional.ofNullable(monitoring.getHainanVotes())
                                    .orElse(0);
                    monitoring.setFlowTally(flowTally);
                    monitoring.setFlowRatio(BigDecimal.valueOf(flowTally).divide(BigDecimal.valueOf(monitoring.getSendTicket()), 2, BigDecimal.ROUND_UP));
                    if (monitoring.getFlowRatio().compareTo(monitoring.getDirectionIndicator()) > 0) {
                        BigDecimal flowDirectionTest = monitoring.getDirectionStandard().multiply(BigDecimal.valueOf(flowTally));
                        monitoring.setFlowDirectionTest(flowDirectionTest);
                    } else {
                        monitoring.setFlowDirectionTest(BigDecimal.ZERO);
                    }
                }
            } else {
                for (ScWeightFlowDirectionMonitoring monitoring : list) {
                    //包仓重量减日考核重量，小于0，则止损考核为0
                    if (monitoring.getBaleWeight().compareTo(monitoring.getDailyAssessWeight()) > 0) {
                        BigDecimal stopLossAssessment = monitoring.getBaleWeight().subtract(monitoring.getDailyAssessWeight());
                        monitoring.setStopLossAssessment(stopLossAssessment.multiply(monitoring.getAssessmentStandard()));
                    } else {
                        monitoring.setStopLossAssessment(BigDecimal.ZERO);
                    }
                    //均重考核
                    if (monitoring.getPackingWarehouseWeight().compareTo(monitoring.getAverageWeightIndex()) > 0) {
                        BigDecimal weightAssessment = (monitoring.getPackingWarehouseWeight().subtract(monitoring.getAverageWeightIndex()).multiply(BigDecimal.valueOf(monitoring.getStockCount())).multiply(monitoring.getWeightAssessmentStandard()));
                        monitoring.setWeightAssessment(weightAssessment);
                    } else {
                        monitoring.setWeightAssessment(BigDecimal.ZERO);
                    }
                    //流向占比
                    if (monitoring.getFlowRatio().compareTo(monitoring.getDirectionIndicator()) > 0) {
                        BigDecimal flowDirectionTest = monitoring.getDirectionStandard().multiply(BigDecimal.valueOf(monitoring.getFlowTally()));
                        monitoring.setFlowDirectionTest(flowDirectionTest);
                    } else {
                        monitoring.setFlowDirectionTest(BigDecimal.ZERO);
                    }
                }
            }
            List<TableVo> tableVos = new ArrayList<>();
            TableVo tableVo = new TableVo();
            tableVo.setFields("settleDate");
            tableVo.setTranslate("统计日期");
            tableVos.add(tableVo);
            tableVo = new TableVo();
            tableVo.setFields("contractArea");
            tableVo.setTranslate("名称");
            tableVos.add(tableVo);

            tableVo = new TableVo();
            tableVo.setFields("sendTicket");
            tableVo.setTranslate("发件票数");
            tableVo.setIsPoint(1);
            tableVos.add(tableVo);

            tableVo = new TableVo();
            tableVo.setFields("stockCount");
            tableVo.setTranslate("包仓票数");
            tableVo.setIsPoint(2);
            tableVos.add(tableVo);

            tableVo = new TableVo();
            tableVo.setFields("baleWeight");
            tableVo.setTranslate("包仓重量");
            tableVos.add(tableVo);

            tableVo = new TableVo();
            tableVo.setFields("stop");
            tableVo.setTranslate("止损考核");
            List<TableVo> tableSunVos = new ArrayList<>();
            String[] stop = {"dailyAssessWeight", "assessmentStandard", "stopLossAssessment"};
            InitTableVo initTableVo = new InitTableVo();
            initTableVo.setFields(stop);
            initTableVo.setCode("scWeight");
            tableSunVos = tableService.initTable(initTableVo);
            tableVo.setSunList(tableSunVos);
            tableVos.add(tableVo);

            tableVo = new TableVo();
            tableVo.setFields("weight");
            tableVo.setTranslate("均重考核");
            tableSunVos = new ArrayList<>();
            String[] weight = {"packingWarehouseWeight", "averageWeightIndex", "weightAssessmentStandard", "weightAssessment"};
            initTableVo = new InitTableVo();
            initTableVo.setFields(weight);
            initTableVo.setCode("scWeight");
            tableSunVos = tableService.initTable(initTableVo);
            tableVo.setSunList(tableSunVos);
            tableVos.add(tableVo);

            tableVo = new TableVo();
            tableVo.setFields("flow");
            tableVo.setTranslate("流向考核");
            tableSunVos = new ArrayList<>();
            String[] flow = {"ningxiaVotes", "gansuVotes", "qinghaiVotes", "hainanVotes", "flowTally", "flowRatio", "directionIndicator", "flowDirectionTest"};
            initTableVo = new InitTableVo();
            initTableVo.setFields(flow);
            initTableVo.setCode("scWeight");
            tableSunVos = tableService.initTable(initTableVo);
            for (TableVo sunVo : tableSunVos) {
                String fields = sunVo.getFields();
                switch (fields) {
                    case "ningxiaVotes":
                        sunVo.setIsPoint(3);
                        break;
                    case "gansuVotes":
                        sunVo.setIsPoint(4);
                        break;
                    case "qinghaiVotes":
                        sunVo.setIsPoint(5);
                        break;
                    case "hainanVotes":
                        sunVo.setIsPoint(6);
                        break;
                }
            }
            tableVo.setSunList(tableSunVos);
            tableVos.add(tableVo);

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("list", PageInfo.info(list));
            jsonObject.put("fields", tableVos);

            if (list == null || list.size() == 0) {
                return R.fail("暂无数据");
            } else {
                return R.ok(jsonObject);
            }
        }
        if (vo.getNetworkLevel() == 1) {
            List<ScWeightFlowDirectionMonitoringClient> list = detailMapper.selectScWeightFlowDirectionMonitoring1(vo);
            if (list == null || list.size() == 0) {
                PageHelper.startPage(vo.getPageDate());
                list = clientMapper.collectClient(vo);
                for (ScWeightFlowDirectionMonitoringClient client : list) {

                    Integer flowTally = Optional.ofNullable(client.getNingxiaVotes())
                            .orElse(0) +
                            Optional.ofNullable(client.getGansuVotes())
                                    .orElse(0) +
                            Optional.ofNullable(client.getQinghaiVotes())
                                    .orElse(0) +
                            Optional.ofNullable(client.getHainanVotes())
                                    .orElse(0);
                    client.setFlowTally(flowTally);
                    if (client != null && client.getSendTicket() != null && client.getSendTicket() != 0) {
                        client.setFlowRatio(BigDecimal.valueOf(flowTally).divide(BigDecimal.valueOf(client.getSendTicket()), 2, BigDecimal.ROUND_UP));
                    } else {
                        client.setFlowRatio(BigDecimal.ZERO);
                    }
                }
            }
            List<TableVo> tableVos = new ArrayList<>();
            TableVo tableVo = new TableVo();
            tableVo.setFields("settleDate");
            tableVo.setTranslate("统计日期");
            tableVos.add(tableVo);

            tableVo = new TableVo();
            tableVo.setFields("contractArea");
            tableVo.setTranslate("名称");
            tableVos.add(tableVo);

            tableVo = new TableVo();
            tableVo.setFields("sendTicket");
            tableVo.setTranslate("发件票数");
            tableVo.setIsPoint(1);
            tableVos.add(tableVo);

            tableVo = new TableVo();
            tableVo.setFields("stockCount");
            tableVo.setTranslate("包仓票数");
            tableVo.setIsPoint(2);
            tableVos.add(tableVo);

            tableVo = new TableVo();
            tableVo.setFields("baleWeight");
            tableVo.setTranslate("包仓重量");
            tableVos.add(tableVo);

            tableVo = new TableVo();
            tableVo.setFields("packingWarehouseWeight");
            tableVo.setTranslate("包仓均重");
            tableVos.add(tableVo);

            tableVo = new TableVo();
            tableVo.setFields("ningxiaVotes");
            tableVo.setTranslate("宁夏票数");
            tableVo.setIsPoint(3);
            tableVos.add(tableVo);

            tableVo = new TableVo();
            tableVo.setFields("gansuVotes");
            tableVo.setTranslate("甘肃票数");
            tableVo.setIsPoint(4);
            tableVos.add(tableVo);

            tableVo = new TableVo();
            tableVo.setFields("qinghaiVotes");
            tableVo.setTranslate("青海票数");
            tableVo.setIsPoint(5);
            tableVos.add(tableVo);

            tableVo = new TableVo();
            tableVo.setFields("hainanVotes");
            tableVo.setTranslate("海南票数");
            tableVo.setIsPoint(6);
            tableVos.add(tableVo);

            tableVo = new TableVo();
            tableVo.setFields("flowTally");
            tableVo.setTranslate("流向票数合计");
            tableVos.add(tableVo);

            tableVo = new TableVo();
            tableVo.setFields("flowRatio");
            tableVo.setTranslate("流向占比");
            tableVos.add(tableVo);

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("list", PageInfo.info(list));
            jsonObject.put("fields", tableVos);

            if (list == null || list.size() == 0) {
                return R.fail("暂无数据");
            } else {
                return R.ok(jsonObject);
            }
        }
        return R.fail();
    }


    public List<ScWeightFlowDirectionMonitoring> collectCache(ScWeightFlowDirectionMonitoringVo vo) {
        List<ScWeightFlowDirectionMonitoring> list = scWeightFlowDirectionMonitoringNewMapper.collect(vo);
        //List<ScWeightFlowDirectionMonitoring> list = scWeightFlowDirectionMonitoringNewMapper.collect(vo);
        for (ScWeightFlowDirectionMonitoring monitoring : list) {
            // 包仓内票数
            Integer stockCount = monitoring.getSendTicket() - scWeightFlowDirectionMonitoringNewMapper.stockCount(vo.getStartTime(), vo.getEndTime());
            monitoring.setStockCount(stockCount);
            //包仓内重量
            BigDecimal baleWeight = scWeightFlowDirectionMonitoringNewMapper.baleWeight(vo.getStartTime(), vo.getEndTime());
            baleWeight = baleWeight.setScale(2, RoundingMode.HALF_UP);
            monitoring.setBaleWeight(baleWeight);
            //止损考核
            if (monitoring.getBaleWeight().compareTo(monitoring.getDailyAssessWeight()) > 0) {
                BigDecimal stopLossAssessment = monitoring.getBaleWeight().subtract(monitoring.getDailyAssessWeight());
                monitoring.setStopLossAssessment(stopLossAssessment.multiply(monitoring.getAssessmentStandard()));
            } else {
                monitoring.setStopLossAssessment(BigDecimal.ZERO);
            }
            // 均重考核-包仓均重
            monitoring.setPackingWarehouseWeight(baleWeight.divide(BigDecimal.valueOf(stockCount), mc));
            if (monitoring.getPackingWarehouseWeight().compareTo(monitoring.getAverageWeightIndex()) > 0) {
                BigDecimal weightAssessment = (monitoring.getPackingWarehouseWeight().subtract(monitoring.getAverageWeightIndex()).multiply(BigDecimal.valueOf(stockCount)).multiply(monitoring.getWeightAssessmentStandard()));
                monitoring.setWeightAssessment(weightAssessment);
            } else {
                monitoring.setWeightAssessment(BigDecimal.ZERO);
            }
            // 流向票数合计
            Integer flowTally = Optional.ofNullable(monitoring.getNingxiaVotes())
                    .orElse(0) +
                    Optional.ofNullable(monitoring.getGansuVotes())
                            .orElse(0) +
                    Optional.ofNullable(monitoring.getQinghaiVotes())
                            .orElse(0) +
                    Optional.ofNullable(monitoring.getHainanVotes())
                            .orElse(0);
            monitoring.setFlowTally(flowTally);
            monitoring.setFlowRatio(BigDecimal.valueOf(flowTally).divide(BigDecimal.valueOf(monitoring.getSendTicket()), 2, BigDecimal.ROUND_UP));
            if (monitoring.getFlowRatio().compareTo(monitoring.getDirectionIndicator()) > 0) {
                BigDecimal flowDirectionTest = monitoring.getDirectionStandard().multiply(BigDecimal.valueOf(5)).multiply(BigDecimal.valueOf(flowTally));
                monitoring.setFlowDirectionTest(flowDirectionTest);
            } else {
                monitoring.setFlowDirectionTest(BigDecimal.ZERO);
            }
        }
        return list;
    }


    public List<ScWeightFlowDirectionMonitoringClient> collectCache1(ScWeightFlowDirectionMonitoringVo vo) {
        List<ScWeightFlowDirectionMonitoringClient> list = detailMapper.selectScWeightFlowDirectionMonitoring1(vo);
        if (list == null || list.size() == 0) {
            list = clientMapper.collectClient(vo);
        }
        //List<ScWeightFlowDirectionMonitoringClient> list = clientMapper.collectClient(vo);
        for (ScWeightFlowDirectionMonitoringClient client : list) {

            Integer flowTally = Optional.ofNullable(client.getNingxiaVotes())
                    .orElse(0) +
                    Optional.ofNullable(client.getGansuVotes())
                            .orElse(0) +
                    Optional.ofNullable(client.getQinghaiVotes())
                            .orElse(0) +
                    Optional.ofNullable(client.getHainanVotes())
                            .orElse(0);
            client.setFlowTally(flowTally);
            if (client != null && client.getSendTicket() != null && client.getSendTicket() != 0) {
                client.setFlowRatio(BigDecimal.valueOf(flowTally).divide(BigDecimal.valueOf(client.getSendTicket()), 2, BigDecimal.ROUND_UP));
            } else {
                client.setFlowRatio(BigDecimal.ZERO);
            }
        }
        return list;

    }


}
